package com.supermap.search.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.supermap.android.maps.BoundingBox;
import com.supermap.android.maps.DefaultItemizedOverlay;
import com.supermap.android.maps.LineOverlay;
import com.supermap.android.maps.MBTilesLayerView;
import com.supermap.android.maps.MapController;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.OverlayItem;
import com.supermap.android.maps.Point2D;
import com.supermap.android.maps.PointOverlay;
import com.supermap.android.maps.PolygonOverlay;
import com.supermap.greendao.CollectBeanDao;
import com.supermap.search.R;
import com.supermap.search.Url_name;
import com.supermap.search.adapter.MyAdapter;
import com.supermap.search.javabean.CollectBean;
import com.supermap.search.javabean.InspectionServerEntity;
import com.supermap.search.javabean.XunJianOneTime;
import com.supermap.search.sys.loc.CoorConvert;
import com.supermap.search.sys.loc.LocationApplication;
import com.supermap.search.sys.loc.LocationService;
import com.supermap.search.utils.NetUtil;
import com.supermap.search.utils.TimeUtils;
import com.supermap.search.utils.ToastUtils;
import com.supermap.search.utils.Utils;
import com.supermap.search.wigdet.CustomPopWindow;
import com.supermap.search.wigdet.CustomProgressBar;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;
import com.yolanda.nohttp.rest.StringRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * 这是主界面
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.ll_pb_shangbao)
    LinearLayout llPbShangbao;
    @BindView(R.id.iv_loc)
    ImageView ivLoc;
    @BindView(R.id.iv_shangbao)
    ImageView ivShangbao;
    @BindView(R.id.iv_cehua)
    ImageView ivCehua;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.ll_denglu)
    LinearLayout llDenglu;
    @BindView(R.id.tbn_xunjian)
    ToggleButton tbnXunjian;
    @BindView(R.id.tbn_dianti)
    ToggleButton tbnDianti;
    @BindView(R.id.tbn_kongtiao)
    ToggleButton tbnKongtiao;
    @BindView(R.id.tbn_paifeng)
    ToggleButton tbnPaifeng;
    @BindView(R.id.tbn_biandian)
    ToggleButton tbnBiandian;
    @BindView(R.id.tbn_xiaofang)
    ToggleButton tbnXiaofang;
    @BindView(R.id.tbn_qita)
    ToggleButton tbnQita;
    @BindView(R.id.tbn_problem)
    ToggleButton tbnProblem;
    @BindView(R.id.right_drawer)
    LinearLayout rightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    private double intLon;//经度
    private double intLat;//纬度
    private LocationService locationService;
    private boolean isloc;//是否定位
    private BoundingBox mapViewBounds;


    private CustomProgressBar dialog;
    private MBTilesLayerView mbTilesLayerView2;
    private MBTilesLayerView mbTilesLayerView3;
    private MBTilesLayerView mbTilesLayerView4;
    private MBTilesLayerView mbTilesLayerView1;
    private MBTilesLayerView mbTilesLayerView5;


    private RequestQueue requestQueue;
    private StringRequest stringRequest;
    private CollectBeanDao dao;

    private CustomPopWindow customPopWindow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //初始化加载弹框
        dialog = new CustomProgressBar(this);
        dialog.show();

        init();

        initMap();

        //初始化地图上的点线面
        initMapRes();

        //初始化触屏overlay
        touchOverlay = new TouchOverlay();

        requestQueue = NoHttp.newRequestQueue();

        dao = LocationApplication.getInstance().getDaoSession().getCollectBeanDao();


        if(getIntent().getIntExtra("xunjian",0)==8){
            String x = getIntent().getStringExtra("x");
            String y = getIntent().getStringExtra("y");
            xunjianX =  Double.parseDouble(x);
            xunjianY =  Double.parseDouble(y);
            if (!mapView.getOverlays().contains(touchOverlay)) {
                mapView.getOverlays().add(touchOverlay);
            }
            Point2D point2D = new Point2D(xunjianX, xunjianY);
//   这里给屏幕显示个点击后的红色
            OverlayItem overlayItem = new OverlayItem(point2D, "", "");
            overlayItem.setAlignment(-1);
            guZhangMarkerOverlay.clear();
            guZhangMarkerOverlay.addItem(overlayItem);
            mapView.getOverlays().add(guZhangMarkerOverlay);

            mapView.invalidate();
        }
    }


    //初始化map
    public void initMap() {

        //构造离线图层，Mbtiles文件所在的路径相对于移动端设备sdcard的路径
        mbTilesLayerView1 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Firstfloor.smtiles");
        mbTilesLayerView2 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Secondfloor.smtiles");
        mbTilesLayerView3 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Thirdfloor.smtiles");
        mbTilesLayerView4 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Fourthfloor.smtiles");
        mbTilesLayerView5 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/supermap_sqlite/巡检线路图.smtiles");
        //添加离线图层
        mapView.addLayer(mbTilesLayerView1);
        //启用内置的缩放控件

        mapView.setBuiltInZoomControls(false);
        mapView.setClickable(true);
        mapView.addMapViewEventListener(new MapViewEventAdapter());
        mapView.invalidate();
        dialog.dismiss();
    }


    /**
     * 初始化资源标注
     */
    public void initMapRes() {
        /**
         113.301030,23.400735
         113.300476,23.399936
         113.301479,23.400093
         113.301955,23.400633
         113.300405,23.400975
         113.299927,23.400381
         113.300003,23.399927
         113.300355,23.399584
         */

        List<InspectionServerEntity> outList = new ArrayList<>();
        // 0正常 1待维修 2待认证
        CollectBean collectBean1 = new CollectBean(001L, "消火栓", "0", "T2航站楼", "2", "1", "113.301030", "23.400735");
        CollectBean collectBean2 = new CollectBean(002L, "光缆", "1", "T2航站楼", "2", "2", "113.300476,113.300003", "23.399936,23.400975");
        CollectBean collectBean3 = new CollectBean(003L, "电梯面", "2", "T2航站楼", "2", "0", "113.299927,113.300003,113.300355", "23.400381,23.399927,23.399584");
        ArrayList<XunJianOneTime> xunJianOneTime1 = new ArrayList<>();
        ArrayList<XunJianOneTime> xunJianOneTime2 = new ArrayList<>();
        ArrayList<XunJianOneTime> xunJianOneTime3 = new ArrayList<>();
        XunJianOneTime bean1 = new XunJianOneTime(001L, "001", "严重", "灭火去不能使用", "", "电梯设备", "", "", "1", "113.301030", "23.400735", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        XunJianOneTime bean2 = new XunJianOneTime(001L, "001", "无影响", "正常", "", "电梯设备", "", "", "0", "113.300003", "23.399927", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        xunJianOneTime1.add(bean1);
        xunJianOneTime1.add(bean2);
        XunJianOneTime bean3 = new XunJianOneTime(001L, "002", "无影响", "正常","", "电梯设备", "", "", "0", "113.300476", "23.399936", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        XunJianOneTime bean4 = new XunJianOneTime(001L, "002","严重", "光缆内线暴露","", "电梯设备", "已修复,请领导检查", "", "2", "113.300003", "23.400975", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        xunJianOneTime2.add(bean3);
        xunJianOneTime2.add(bean4);

        XunJianOneTime bean5 = new XunJianOneTime(001L, "003", "无影响", "正常","", "电梯设备", "", "", "0", "113.299927", "23.400381", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        XunJianOneTime bean6 = new XunJianOneTime(001L, "003","严重", "光缆内线暴露","", "电梯设备", "已修复,请领导检查", "", "2", "113.300355", "23.399584", TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()), TimeUtils.date2String(new Date()));
        xunJianOneTime3.add(bean5);
        xunJianOneTime3.add(bean6);

        outList.add(new InspectionServerEntity(collectBean1, xunJianOneTime1));
        outList.add(new InspectionServerEntity(collectBean2, xunJianOneTime2));
        outList.add(new InspectionServerEntity(collectBean3, xunJianOneTime3));

        for (InspectionServerEntity entity : outList) {
            CollectBean collectBean = entity.getCollectBean();
            if ("0".equals(collectBean.getResType())) {
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                //添加点
                Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                PointOverlay pointOverlay = new PointOverlay(point2D, MainActivity.this);
                pointOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        if (customPopWindow != null) {
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).setView(view).create();
                        customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                        ListView listView = view.findViewById(R.id.listview);
                        listView.setAdapter(new MyAdapter<XunJianOneTime>(entity.getList(), R.layout.pop_feature_info_item) {
                            @Override
                            public void bindView(ViewHolder holder, XunJianOneTime obj) {
                                holder.setText(R.id.tv_build, collectBean.getBuild());
                                holder.setText(R.id.tv_floor, collectBean.getFloor());
                                holder.setText(R.id.res_name, collectBean.getResName());
                                holder.setText(R.id.tv_hisotry, obj.getReportTime());
                                holder.setText(R.id.tv_describe, obj.getWentiqingkuang());
                            }
                        });
                    }
                });
                mapView.getOverlays().add(pointOverlay);
            } else if ("1".equals(collectBean.getResType())) {
                List<Point2D> point2DS = new ArrayList<Point2D>();
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                String[] longitudes = longitude.split(",");
                String[] latitudes = latitude.split(",");
                for (int i = 0; i < longitudes.length; i++) {
                    longitude = longitudes[i];
                    latitude = latitudes[i];
                    Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    point2DS.add(point2D);
                }
                //添加线
                LineOverlay lineOverlay = new LineOverlay(getLinePaint());
                lineOverlay.setData(point2DS);
                lineOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        if (customPopWindow != null) {
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).setView(view).create();
                        customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                        ListView listView = view.findViewById(R.id.listview);
                        listView.setAdapter(new MyAdapter<XunJianOneTime>(entity.getList(), R.layout.pop_feature_info_item) {
                            @Override
                            public void bindView(ViewHolder holder, XunJianOneTime obj) {
                                holder.setText(R.id.tv_build, collectBean.getBuild());
                                holder.setText(R.id.tv_floor, collectBean.getFloor());
                                holder.setText(R.id.res_name, collectBean.getResName());
                                holder.setText(R.id.tv_hisotry, obj.getReportTime());
                                holder.setText(R.id.tv_describe, obj.getWentiqingkuang());
                            }
                        });

                    }
                });
                mapView.getOverlays().add(lineOverlay);
            } else if ("2".equals(collectBean.getResType())) {
                List<Point2D> point2DS = new ArrayList<Point2D>();
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                String[] longitudes = longitude.split(",");
                String[] latitudes = latitude.split(",");
                for (int i = 0; i < longitudes.length; i++) {
                    longitude = longitudes[i];
                    latitude = latitudes[i];
                    Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    point2DS.add(point2D);
                }
                //添加面
                PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
                polygonOverlay.setData(point2DS);
                polygonOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        if (customPopWindow != null) {
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(false).setView(view).create();
                        customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                        ListView listView = view.findViewById(R.id.listview);
                        listView.setAdapter(new MyAdapter<XunJianOneTime>(entity.getList(), R.layout.pop_feature_info_item) {
                            @Override
                            public void bindView(ViewHolder holder, XunJianOneTime obj) {
                                holder.setText(R.id.tv_build, collectBean.getBuild());
                                holder.setText(R.id.tv_floor, collectBean.getFloor());
                                holder.setText(R.id.res_name, collectBean.getResName());
                                holder.setText(R.id.tv_hisotry, obj.getReportTime());
                                holder.setText(R.id.tv_describe, obj.getWentiqingkuang());
                            }
                        });

                    }
                });
                mapView.getOverlays().add(polygonOverlay);
            }
        }

    }


    @Override
    protected void onDestroy() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onDestroy();
    }

    private double xunjianX;
    private double xunjianY;
    @Override
    protected void onStart() {
        super.onStart();
        locationService = ((LocationApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();// 定位SDK
        guZhangMarkerOverlay.clear();
        if (getIntent().getIntExtra("shangbao", 3) == 11) {
            isguzhang = true;
        }

        if(getIntent().getIntExtra("xunjian",0)==8){
            String x = getIntent().getStringExtra("x");
            String y = getIntent().getStringExtra("y");
            xunjianX =  Double.parseDouble(x);
            xunjianY =  Double.parseDouble(y);
            if (!mapView.getOverlays().contains(touchOverlay)) {
                mapView.getOverlays().add(touchOverlay);
            }
            Point2D point2D = new Point2D(xunjianX, xunjianY);
//   这里给屏幕显示个点击后的红色
            OverlayItem overlayItem = new OverlayItem(point2D, "", "");
            overlayItem.setAlignment(-1);
            guZhangMarkerOverlay.clear();
            guZhangMarkerOverlay.addItem(overlayItem);
            mapView.getOverlays().add(guZhangMarkerOverlay);

            mapView.invalidate();
        }
    }


    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    BDLocation location;
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //坐标转换
                double[] lnglat = CoorConvert.Gjc2Wgs84(location.getLongitude(), location.getLatitude());
                intLon = lnglat[0];//100
                intLat = lnglat[1];//30
                MainActivity.this.location = location;
            }
        }

    };


    /**
     * 画出GPS图标
     */
    public void drawGps() {

        double x = location.getLongitude();
        double y = location.getLatitude();
        Drawable drawableBlue = getResources().getDrawable(R.mipmap.location_checked);
        DefaultItemizedOverlay overlay = new DefaultItemizedOverlay(drawableBlue);
        OverlayItem overlayItem2 = new OverlayItem(new Point2D(x, y), "", "");
        overlay.addItem(overlayItem2);
        mapView.getOverlays().add(overlay);
        Point2D point2D = new Point2D(x, y);
        MapController controller = mapView.getController();
        controller.setCenter(point2D);
        controller.setZoom(10);

        // 重新onDraw一次
        mapView.invalidate();
    }

    private void init() {
        isloc = false;
        sp = getSharedPreferences(Url_name.SP, 0);
        //为侧滑菜单设置的监听；
        drawerLayoutSet();

        Drawable drawableGuZhang = getResources().getDrawable(R.mipmap.guzhang);
        guZhangMarkerOverlay = new DefaultItemizedOverlay(drawableGuZhang);
    }

    @OnCheckedChanged({R.id.tbn_xunjian, R.id.tbn_dianti, R.id.tbn_kongtiao, R.id.tbn_paifeng, R.id.tbn_biandian, R.id.tbn_xiaofang, R.id.tbn_qita, R.id.tbn_problem})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        switch (id) {
            case R.id.tbn_xunjian:
                if (isChecked) {
                    //已经开启巡检了，关闭巡检
                    mapView.addLayer(mbTilesLayerView2);
                } else {
                    //已经开启巡检了，关闭巡检
                    mapView.removeLayer(mbTilesLayerView2);
                }
                break;
            case R.id.tbn_dianti:
                break;
            case R.id.tbn_kongtiao:
                break;
            case R.id.tbn_paifeng:
                break;
            case R.id.tbn_biandian:
                break;
            case R.id.tbn_xiaofang:
                break;
            case R.id.tbn_qita:
                break;
            case R.id.tbn_problem:
                break;

        }
    }


    private void drawerLayoutSet() {
        // 关闭手势滑动
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // 打开手势滑动
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
//                检查用户是否登录
                checkUser();
//                关闭mapview获得焦点、
                mapView.setClickable(false);
                // 启用内置放大缩小控件
                mapView.setBuiltInZoomControls(false);
//                显示放大缩小控件
                mapView.displayZoomControls(false);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                // 关闭手势滑动
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                //                打开mapview获得焦点、
                mapView.setClickable(true);
                // 启用内置放大缩小控件
                mapView.setBuiltInZoomControls(true);
//                显示放大缩小控件
                mapView.displayZoomControls(true);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkUser();
    }

    private SharedPreferences sp;

    private void checkUser() {
        if (sp.getBoolean("state", false)) {
//            登陆了
            userName.setText(sp.getString("name", ""));
        } else {
//            没有登陆了
            userName.setText("点击登陆");
        }
    }

    public boolean onTouchEvent(MotionEvent event) {
        //屏幕点击事件
        int iAction = event.getAction();
        if (iAction == MotionEvent.ACTION_CANCEL || iAction == MotionEvent.ACTION_DOWN
                || iAction == MotionEvent.ACTION_MOVE) {
            return false;
        }
        if (isguzhang) {
            //开启故障
            int x = (int) event.getX();
            int y = (int) event.getY();
            doGuZhang(x, y);
        }
        return super.onTouchEvent(event);
    }

    private DefaultItemizedOverlay guZhangMarkerOverlay;
    private boolean isguzhang = false;

    private void doGuZhang(int x, int y) {
        Point2D point2D = mapView.toMapPoint(x, y);
//   这里给屏幕显示个点击后的红色
        OverlayItem overlayItem = new OverlayItem(point2D, "", "");
        overlayItem.setAlignment(-1);
        guZhangMarkerOverlay.clear();
        guZhangMarkerOverlay.addItem(overlayItem);
        mapView.getOverlays().add(guZhangMarkerOverlay);
        mapView.invalidate();
        final Intent intent = new Intent();
        intent.putExtra("X", point2D.getX());
        intent.putExtra("Y", point2D.getY());
        final AlertDialog.Builder isExit = new AlertDialog.Builder(MainActivity.this);
        //设置对话框标题
        isExit.setTitle("温馨提醒：请将地图调至最大缩放级别在进行定位！");
        //设置对话框消息
        isExit.setMessage("你选定好位置了么?");
        // 添加选择按钮并注册监听
        isExit.setPositiveButton("确定，我选择好了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(3, intent);
                isguzhang = false;
                MainActivity.this.finish();
            }

        });
        isExit.setNegativeButton("没有，重新选择", null);
        //对话框显示
        isExit.show();
    }


    @OnClick({R.id.iv_loc, R.id.ll_denglu, R.id.iv_shangbao, R.id.iv_cehua, R.id.iv_collect})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_loc:
                //定位按钮逻辑
                findloc();
                break;
            case R.id.ll_denglu:
                //登陆按钮逻辑
                login();
                break;
            case R.id.iv_shangbao:
                //上报的逻辑
                if (sp.getBoolean("state", false)) {
                    startActivity(new Intent(MainActivity.this, ShangBaoActivity.class));
                } else {
                    Toast.makeText(MainActivity.this, "请先登录才有使用权限！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_cehua:
                //这里侧滑的功能
                cehua();
                break;
            case R.id.iv_collect:
                //这里侧滑的功能
                addCollect();
                break;
        }
    }


    private void cehua() {
        //这里侧滑的功能
        if (!drawerLayout.isDrawerOpen(rightDrawer)) {
            drawerLayout.openDrawer(rightDrawer);
        }
    }


    private void login() {
        //登陆
        Intent intent = new Intent(MainActivity.this, UserActivity.class);
        startActivity(intent);

    }

    private void findloc() {
        //定位的逻辑
        if (isloc) {
            //定位了，取消定位
            ivLoc.setImageResource(R.mipmap.locno);
            isloc = false;
        } else {
            mapViewBounds = mapView.getBounds();
            if (mapViewBounds.contains(new Point2D(intLon, intLat)) && location != null) {
                drawGps();
                String addrStr = location.getAddrStr();
                ToastUtils.showShortToast(addrStr);
                mapView.getController().setCenter(new Point2D(intLon, intLat));
                //                    没定位,开启定位操作
                ivLoc.setImageResource(R.mipmap.locyes);
                isloc = true;
                //gps定位后在地图范围内
                mapView.invalidate();
            } else {
                Toast.makeText(MainActivity.this, "你不在地图范围内！", Toast.LENGTH_SHORT).show();
//                        mapView.getController().setCenter(new Point2D(113.80551312, 22.63319908));
            }
        }
    }


    /**
     * ---------------------------------------------------------------------------------------------
     * 采集资源
     */

    // 存放绘制线或面的点集合
    private List<Point2D> geoPoints = new ArrayList<Point2D>();
    private List<PointOverlay> pointOverlays = new ArrayList<PointOverlay>(1);
    // 存放所需绘制的线对象集合
    private List<LineOverlay> lineOverlays = new ArrayList<LineOverlay>(1);
    // 默认的绘制线对象
    // private LineOverlay firstLineOverlay;
    // 存放所需绘制的面对象集合
    private List<PolygonOverlay> polygonOverlays = new ArrayList<PolygonOverlay>(1);
    // 默认的绘制面对象
    // private PolygonOverlay firstPolygonOverlay;
    // 触屏Overlay,用来获取点坐标
    private TouchOverlay touchOverlay;
    // 绘制要素状态
    private int drawStatic = 1;// 1代表绘制线，2表示绘制面，0代表绘制点
    // 单个绘制对象绘制完成的标志
    private boolean addOverlayOver = false;
    private boolean useDraw = true;
    private static final int README_DIALOG = 9;
    // 触屏的x坐标
    private int touchX;

    // 触屏的y坐标
    private int touchY;

    private boolean isMultiTouch = false;

    public void addCollect() {

        mapView.getOverlays().removeAll(pointOverlays);
        mapView.getOverlays().removeAll(lineOverlays);
        mapView.getOverlays().removeAll(polygonOverlays);
        mapView.setUseDoubleTapEvent(true);
        useDraw = true;
        pointOverlays.clear();
        polygonOverlays.clear();
        geoPoints.clear();
        lineOverlays.clear();
        isOnLongTouch = false;

        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_res_type, null);
        CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this).setView(inflate).enableBackgroundDark(true).setOutsideTouchable(false).create();
        customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
        inflate.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioGroup radioGroup = inflate.findViewById(R.id.rg_type);
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (checkedRadioButtonId == -1) {
                    ToastUtils.showShortToast("请选择采集类型");
                    return;
                } else {
                    customPopWindow.dissmiss();
                }
                switch (checkedRadioButtonId) {
                    case R.id.dian:
                        // 添加PointOverlay绘点，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        drawStatic = 0;
                        // 不启用双击事件触发放大地图
                        mapView.setUseDoubleTapEvent(false);
                        break;
                    case R.id.xian:
                        // 添加LineOverlay绘线，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        addLineOverLayer();
                        drawStatic = 1;
                        mapView.setUseDoubleTapEvent(false);
                        break;
                    case R.id.mian:
                        // 添加PolygonOverlay绘面，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        addPolygonOverLayer();
                        drawStatic = 2;
                        mapView.setUseDoubleTapEvent(false);
                        break;
                }


            }
        });

        inflate.findViewById(R.id.btn_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopWindow.dissmiss();
            }
        });
        inflate.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopWindow.dissmiss();
            }
        });

    }


    /**
     * 添加面标注
     */
    private void addPolygonOverLayer() {
        PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
        mapView.getOverlays().add(polygonOverlay);
        polygonOverlays.add(polygonOverlay);
    }

    /**
     * 添加线标注
     */
    private void addLineOverLayer() {
        LineOverlay lineOverlay = new LineOverlay(getLinePaint());
        mapView.getOverlays().add(lineOverlay);
        lineOverlays.add(lineOverlay);
    }


    /**
     * 绘线风格
     *
     * @return
     */
    public static Paint getLinePaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.argb(200, 10, 230, 250));
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        return paint;

    }

    /**
     * 绘面风格
     *
     * @return
     */
    public static Paint getPolygonPaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.argb(200, 10, 230, 250));
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        return paint;

    }


    /**
     * 给Overlay设置点集合，开始绘制对象，并刷新地图
     *
     * @param overlay
     * @param gps
     */
    private void setOverlayData(Overlay overlay, List<Point2D> gps) {
        if (overlay == null) {
            return;
        }
        List<Point2D> geoPointList = new ArrayList<Point2D>();
        if (gps != null && gps.size() > 0) {
            copyList(gps, geoPointList);
        } else if (geoPoints.size() > 0) {
            copyList(geoPoints, geoPointList);
        }
        if (geoPointList.size() > 0) {
            if (overlay instanceof LineOverlay) {
                ((LineOverlay) overlay).setData(geoPointList);
            } else if (overlay instanceof PolygonOverlay) {
                ((PolygonOverlay) overlay).setData(geoPointList);
            }
            mapView.invalidate();
        }
    }

    /**
     * list复制
     *
     * @param sourcegps
     * @param targetgps
     */
    private void copyList(List<Point2D> sourcegps, List<Point2D> targetgps) {
        for (int i = 0; i < sourcegps.size(); i++) {
            targetgps.add(new Point2D(sourcegps.get(i)));
        }
    }

    /**
     * 设置标注的数据
     *
     * @param overlay
     */
    private void setOverlayData(Overlay overlay) {
        setOverlayData(overlay, null);
    }

    /**
     * 触屏Overlay
     */
    class TouchOverlay extends Overlay {
        private List<Point> movePoints = new ArrayList<Point>();

        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            if (useDraw) {
                if (event.getPointerCount() > 1) {// 发生多点触碰
                    isMultiTouch = true;
                }

                if (isOnLongTouch) {
                    return false;
                }


                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (movePoints.size() > 1) {// 如果发生平移，不绘制
                        double distance = 0;
                        for (int i = movePoints.size() - 1; i > 0; i--) {
                            double ds = Math.pow((movePoints.get(i).x - movePoints.get(i - 1).x), 2)
                                    + Math.pow((movePoints.get(i).y - movePoints.get(i - 1).y), 2);
                            if (ds > distance) {
                                distance = ds;
                            }
                        }
                        if (distance > 16) {
                            return false;
                        }
                    }
                    if (isMultiTouch) {// 如果发生多点触碰，不绘制
                        isMultiTouch = false;
                        return false;
                    }
                    // if(isDoubleTouch){//如果发生双击，只绘制第一次的点
                    // isDoubleTouch = false;
                    // return true;
                    // }
                    touchX = Math.round(event.getX());
                    touchY = Math.round(event.getY());
                    // 记录点击位置
                    Point2D touchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);

                    // 当addOverlayOver为true时，当前对象绘制结束，根据绘制状态，选择创建新的绘制对象加入绘制对象集合中，并置 addOverlayOver为false
                    if (addOverlayOver) {
                        // Log.i("iserver", "onTouchEvent");
                        if (drawStatic == 1) {
                            LineOverlay lineOverlay = new LineOverlay(getLinePaint());
                            mapView.getOverlays().add(lineOverlay);
                            // Log.i("iserver", "lineOverlays前个数：" + lineOverlays.size());
                            lineOverlays.add(lineOverlay);
                            // Log.i("iserver", "lineOverlays后个数：" + lineOverlays.size());
                        } else if (drawStatic == 2) {
                            PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
                            mapView.getOverlays().add(polygonOverlay);
                            polygonOverlays.add(polygonOverlay);
                        }
                        geoPoints.clear();
                        addOverlayOver = false;
                    }

                    if (drawStatic == 1 || drawStatic == 2) {
                        if (!geoPoints.contains(touchGeoPoint)) {
                            // Log.i("iserver", "touchGeoPoint");
                            geoPoints.add(touchGeoPoint);
                        }
                    }

                    if (drawStatic == 0) {// 0代表绘制点
                        mapView.getOverlays().removeAll(pointOverlays);
                        mapView.getOverlays().removeAll(lineOverlays);
                        mapView.getOverlays().removeAll(polygonOverlays);
                        Log.e("onTouch", ">>>>>>>>>>>>>>>>>>>>>>onTouch<<<<<<<<<<<<<<<<<<<<<<<");
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        PointOverlay pointOverlay = new PointOverlay(touchGeoPoint, MainActivity.this);
                        mapView.getOverlays().add(pointOverlay);
                        geoPoints.clear();
                        geoPoints.add(touchGeoPoint);
                        pointOverlays.add(pointOverlay);
                        mapView.invalidate();
                    }

                    if (drawStatic == 1) {// 1代表绘制线
                        setOverlayData(lineOverlays.get(lineOverlays.size() - 1));
                        // mapView.invalidate();
                    } else if (drawStatic == 2) {// 2表示绘制面
                        setOverlayData(polygonOverlays.get(polygonOverlays.size() - 1));
                        //mapView.invalidate();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    movePoints.clear();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    movePoints.add(new Point(Math.round(event.getX()), Math.round(event.getY())));
                }
            }
            return false;
        }
    }

    /**
     * MapView事件处理适配器，提供长按事件的实现
     */
    private boolean isOnLongTouch = false;

    class MapViewEventAdapter implements MapView.MapViewEventListener {

        private View view;
        private CustomPopWindow inspectionPopWindow;

        @Override
        public void moveStart(MapView paramMapView) {

        }

        @Override
        public void move(MapView paramMapView) {

        }

        @Override
        public void moveEnd(MapView paramMapView) {

        }

        @Override
        public void touch(MapView paramMapView) {

        }

        @Override
        public void longTouch(MapView paramMapView) {
            Log.i("iserver", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>longTouch<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            //防止
            if (geoPoints.isEmpty() && lineOverlays.isEmpty() && polygonOverlays.isEmpty()) {
                return;
            }
            isOnLongTouch = true;

            //以 长按事件 作为绘制当前线面对象结束的标志
            if (drawStatic == 1 || drawStatic == 2) {
                addOverlayOver = true;
                mapView.setUseDoubleTapEvent(false);
                useDraw = false;
            }
            view = LayoutInflater.from(MainActivity.this).inflate(R.layout.window_collection_detail, null);

            CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
            inspectionPopWindow = popupWindowBuilder.setView(view).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mapView.getOverlays().removeAll(pointOverlays);
                    mapView.getOverlays().removeAll(lineOverlays);
                    mapView.getOverlays().removeAll(polygonOverlays);
                    mapView.setUseDoubleTapEvent(false);
                    mapView.invalidate();
                    useDraw = false;
                    pointOverlays.clear();
                    polygonOverlays.clear();
                    geoPoints.clear();
                    lineOverlays.clear();
                    isOnLongTouch = false;
                }
            }).enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).create();
            inspectionPopWindow.showAtLocation(mapView, Gravity.BOTTOM, 0, 0);
            view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText editText = view.findViewById(R.id.et_build);
                    EditText editFloor = view.findViewById(R.id.et_floor);
                    EditText editResName = view.findViewById(R.id.et_resname);
                    Spinner spinner = view.findViewById(R.id.sp_res_type);
                    EditText editRemark = view.findViewById(R.id.et_remark);
                    String resType = spinner.getSelectedItem().toString();
                    String build = editText.getText().toString();
                    String floor = editFloor.getText().toString();
                    String resName = editResName.getText().toString();
                    String longitude = "";
                    String latitude = "";
                    for (int i = 0; i < geoPoints.size(); i++) {
                        Point2D point2D = geoPoints.get(i);
                        double x = point2D.getX();
                        double y = point2D.getY();

                        if (i == geoPoints.size() - 1) {
                            longitude += x;
                            latitude += y;
                        } else {
                            longitude += x + ",";
                            latitude += y + ",";
                        }
                    }

                    CollectBean collectBean = new CollectBean(null, resName, resType, build, floor, "0", longitude, latitude);

                    if (NetUtil.isNetworkAvailable(Utils.getContext())) {
                        stringRequest = new StringRequest(Url_name.POST_COLLECT, RequestMethod.POST);
                        stringRequest.add("resName", resName);
                        stringRequest.add("resType", resName);
                        stringRequest.add("build", resName);
                        stringRequest.add("floor", resName);
                        stringRequest.add("state", "0");
                        stringRequest.add("longitude", longitude);
                        stringRequest.add("latitude", latitude);
                        requestQueue.add(1, stringRequest, new SimpleResponseListener<String>() {

                            @Override
                            public void onSucceed(int what, Response<String> response) {
                                ToastUtils.showShortToast("采集成功~");
                                inspectionPopWindow.dissmiss();
                            }

                            @Override
                            public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
                                saveLocalCollect(collectBean);
                                ToastUtils.showShortToast("上传失败，已保存本地");
                                inspectionPopWindow.dissmiss();
                            }
                        });

                    } else {
                        saveLocalCollect(collectBean);
                        ToastUtils.showShortToast("无网络，已保存本地");
                        inspectionPopWindow.dissmiss();
                    }

                }
            });
            view.findViewById(R.id.ib_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (inspectionPopWindow != null) {
                        inspectionPopWindow.dissmiss();
                    }
                }
            });
        }

        @Override
        public void zoomStart(MapView paramMapView) {

        }

        @Override
        public void zoomEnd(MapView paramMapView) {

        }

        @Override
        public void mapLoaded(MapView paramMapView) {

        }
    }


    private void saveLocalCollect(CollectBean collectBean) {
        CollectBeanDao.createTable(LocationApplication.getInstance().getDaoSession().getDatabase(), true);
        dao.insert(collectBean);
    }


    @Override
    public void onBackPressed() {
        AlertDialog.Builder isExit = new AlertDialog.Builder(this);
        //设置对话框标题
        isExit.setTitle("温馨提醒");
        //设置对话框消息
        isExit.setMessage("确定要退出吗?");
        // 添加选择按钮并注册监听
        isExit.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MainActivity.this.finish();
            }

        });
        isExit.setNegativeButton("取消", null);
        //对话框显示
        isExit.show();
    }

}